package cn.itsource.ymcc.exception;

import cn.itsource.ymcc.constant.ErrorConstantCode;
import cn.itsource.ymcc.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;

@RestControllerAdvice // 异常做统一的捕获处理
@Slf4j
public class UniformException {

//    /**
//     * 系统的全局异常处理
//     * @return
//     */
//    @ExceptionHandler(Throwable.class)
//    public JSONResult exceptionHander(Throwable throwable){
//        throwable.printStackTrace();
//        log.info("系统异常：{}",throwable.getMessage());
//        return JSONResult.error("网络异常，请稍后再试，我们正在召唤迪迦！！");
//    }


    /**
     * 自定义业务异常处理
     * @return
     */
    @ExceptionHandler(GlobalException.class)
    public JSONResult exceptionHander(GlobalException exception){
        exception.printStackTrace();
        log.info("业务异常：{}",exception.getMessage());
        return JSONResult.error(exception.getMessage(),exception.getCode());
    }


    /**
     * 自定义业务异常处理
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public JSONResult accessDeniedException(AccessDeniedException exception){
        exception.printStackTrace();
        log.info("业务异常：{}",exception.getMessage());
        return JSONResult.error(exception.getMessage()+"，没有权限不允许访问！");
    }

    /**
     * JS303业务异常处理
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult exceptionHander(MethodArgumentNotValidException exception){
        exception.printStackTrace();
        log.info("业务异常：{}",exception.getMessage());
        StringBuffer sb = new StringBuffer();
        exception.getBindingResult().getAllErrors().forEach(e->{
            sb.append(e.getDefaultMessage()).append(",");
        });

        return JSONResult.error(sb.substring(0,sb.length()-1), ErrorConstantCode.PARAMETER_NOT_BE_NULL.getCode());
    }

}
